package com.sgt.frp.service;



import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sgt.frp.VO.FrpConnect;
import com.sgt.frp.apiEnum.ApiEnum;
import com.sgt.frp.excepiton.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ApiService {

    @Value("${baseApi}")
    public String baseApi;

    public List<FrpConnect> getConnectList(){
       List<FrpConnect> listAll=new ArrayList<>();
       List<FrpConnect> httpList = getListByType(ApiEnum.HTTP_CONNECT);
       List<FrpConnect> tcpList = getListByType(ApiEnum.TCP_CONNECT);
       if(!ObjectUtil.isEmpty(httpList)){
           listAll.addAll(httpList);
       }
       if(!ObjectUtil.isEmpty(tcpList)){
           listAll.addAll(tcpList);
       }
       return listAll;
    }


    public List<FrpConnect> getListByType(ApiEnum apienum) {
        List<FrpConnect> connectAll = new ArrayList<>();
        String bodyString = HttpRequest.get(baseApi + apienum.getUrl()).execute().body();
        JSONObject jsonData = JSON.parseObject(bodyString);
        JSONArray connectList = (JSONArray) jsonData.get("proxies");
        if (ObjectUtil.isEmpty(connectList)){
            return null;
        }
        for (int i = 0; i < connectList.size(); i++) {
            JSONObject connectOne = (JSONObject) connectList.get(i);
            JSONObject confOne = (JSONObject) connectOne.get("conf");
            FrpConnect frpConnect=new FrpConnect();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(!ObjectUtil.isEmpty(confOne)){
                frpConnect = JSONObject.parseObject(confOne.toString(), FrpConnect.class);
            }else{
                frpConnect.setName(connectOne.getString("name"));
                frpConnect.setType(apienum.getType());
                try {
                    frpConnect.setCloseTime(sdf.parse("2022-"+connectOne.getString("last_close_time")));
                }catch (ParseException e){
                    throw BusinessException.init("时间解析失败");
                }

            }
            try {
                frpConnect.setStartTime(sdf.parse("2022-"+connectOne.getString("last_start_time")));
            }catch (ParseException e){
                throw BusinessException.init("时间解析失败");
            }
            String status = connectOne.getString("status");
            if(connectOne.getString("status").equals("online")){
                frpConnect.setStatus(1);
            }else{
                frpConnect.setStatus(0);
            }
            connectAll.add(frpConnect);
        }
        return connectAll;
    }
}
